package cn.com.bluemoon.daps.system.service.impl;

import cn.com.bluemoon.daps.common.enums.SystemType;
import cn.com.bluemoon.daps.system.dto.SystemUserDto;
import cn.com.bluemoon.daps.system.entity.DapSystemBizLineDetail;
import cn.com.bluemoon.daps.system.entity.DapSystemInfo;
import cn.com.bluemoon.daps.system.mapper.DapSystemBizLineDetailMapper;
import cn.com.bluemoon.daps.system.service.DapSystemBizLineDetailService;
import cn.com.bluemoon.daps.system.service.DapSystemInfoService;
import cn.com.bluemoon.daps.system.service.DapSystemUserService;
import cn.com.bluemoon.daps.system.vo.BizLineDetailResponseVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

import static cn.com.bluemoon.daps.system.service.DapSystemUserService.DAP_SYSTEM_LOGIN_USER_SERVICE;

/**
 * <p>
 * 系统与业务线关系信息表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-04-06
 */
@Slf4j
@Service
public class DapSystemBizLineDetailServiceImpl extends ServiceImpl<DapSystemBizLineDetailMapper, DapSystemBizLineDetail>
        implements DapSystemBizLineDetailService {

    @Resource
    private DapSystemInfoService systemInfoService;

    @Resource(name = DAP_SYSTEM_LOGIN_USER_SERVICE)
    private DapSystemUserService systemUserService;

    @Override
    public List<BizLineDetailResponseVo> findDefaultCommonDetailVos() {
        List<DapSystemInfo> res = systemInfoService.list(systemInfoService.bmLambdaQuery()
                .eq(DapSystemInfo::getType, SystemType.WAREHOUSE_SYS).orderByDesc(DapSystemInfo::getUpdateTime));
        return res.stream().map(s -> {
            DapSystemBizLineDetail detail = new DapSystemBizLineDetail();
            detail.setBizLineId(null);
            detail.setSystemId(s.getId());
            detail.setAdmins(null);
            detail.setDevelops(null);
            return detail;
        }).map(this::toBizLineDetailResponseVo).collect(Collectors.toList());
    }

    @Override
    public List<BizLineDetailResponseVo> findDefaultBizLineDetailVosByBizLineId(@NotNull Integer bizLineId) {
        return systemInfoService.list(systemInfoService.bmLambdaQuery()
                .ne(DapSystemInfo::getType, SystemType.WAREHOUSE_SYS)
                .eq(DapSystemInfo::getBizLineId, bizLineId).orderByDesc(DapSystemInfo::getUpdateTime))
                .stream()
                .map(s -> {
                    DapSystemBizLineDetail detail = new DapSystemBizLineDetail();
                    detail.setBizLineId(s.getBizLineId());
                    detail.setSystemId(s.getId());
                    detail.setAdmins(null);
                    detail.setDevelops(null);
                    return detail;
                }).map(this::toBizLineDetailResponseVo).collect(Collectors.toList());
    }

    @Override
    public Optional<BizLineDetailResponseVo> findOneBySystemIdAndBizLineId(String systemId, Integer bizLineId) {
        DapSystemBizLineDetail detail = getOne(bmLambdaQuery().eq(DapSystemBizLineDetail::getBizLineId, bizLineId).eq(DapSystemBizLineDetail::getSystemId, systemId).last(" limit 1"));
        return Optional.ofNullable(detail).map(this::toBizLineDetailResponseVo);
    }

    @Override
    public List<BizLineDetailResponseVo> findBizLineDetailVos(@NotNull Integer bizLineId) {
        // 系统id+业务线id获取关系
        List<BizLineDetailResponseVo> vos = new ArrayList<>();
        List<DapSystemBizLineDetail> details = findByBizLineId(bizLineId);
        for (DapSystemBizLineDetail vo : details) {
            vos.add(toBizLineDetailResponseVo(vo));
        }
        Map<String, List<BizLineDetailResponseVo>> sysAndDetails = vos.stream().collect(Collectors.groupingBy(BizLineDetailResponseVo::getSystemId));
        // 补上公共的
        List<BizLineDetailResponseVo> commonDetailVos = findDefaultCommonDetailVos();
        for (BizLineDetailResponseVo each : commonDetailVos) {
            if (!sysAndDetails.containsKey(each.getSystemId())) {
                each.setBizLineId(bizLineId);
                vos.add(each);
            }
        }
        // 补上当前业务id相关的非数仓系统
        List<BizLineDetailResponseVo> bizLineVos = findDefaultBizLineDetailVosByBizLineId(bizLineId);
        for (BizLineDetailResponseVo each : bizLineVos) {
            if (!sysAndDetails.containsKey(each.getSystemId())) {
                each.setBizLineId(bizLineId);
                vos.add(each);
            }
        }
        return vos;
    }

    @Override
    public void resetBizLineDetails(Integer bizLineId, List<DapSystemBizLineDetail> details) {
        remove(bmLambdaUpdate().eq(DapSystemBizLineDetail::getBizLineId, bizLineId));
        saveBatch(details);
        log.info("重置业务线{}的系统与用户关系", bizLineId);
    }

    @Override
    public boolean removeByBizLineId(Integer bizLineId) {
        boolean remove = remove(bmLambdaUpdate().eq(DapSystemBizLineDetail::getBizLineId, bizLineId));
        return remove;
    }

    @Override
    public List<DapSystemBizLineDetail> findByAdminUserId(String userId) {
        return getBaseMapper().findByAdminUserId(userId);
    }

    @Override
    public List<DapSystemBizLineDetail> findByAdminOrDevelopUserId(String userId) {
        return getBaseMapper().findByAdminOrDevelopUserId(userId);
    }

    private List<DapSystemBizLineDetail> findByBizLineId(Integer bizLineId) {
        return list(bmLambdaQuery().eq(DapSystemBizLineDetail::getBizLineId, bizLineId));
    }

    @Override
    public BizLineDetailResponseVo toBizLineDetailResponseVo(DapSystemBizLineDetail vo) {
        BizLineDetailResponseVo detailVo = new BizLineDetailResponseVo();
        detailVo.setBizLineId(vo.getBizLineId());
        DapSystemInfo systemInfo = systemInfoService.getByIdAsset(vo.getSystemId(), "bizLineId=" + vo.getBizLineId() + ",systemId=" + vo.getSystemId() + "系统信息已被删除");
        detailVo.setSystemId(vo.getSystemId());
        detailVo.setSystemName(systemInfo.getName());
        detailVo.setSystemType(systemInfo.getType().getName());
        List<String> accounts = new ArrayList<>();
        if (vo.getAdmins() != null) {
            detailVo.setAdmins(Arrays.asList(vo.getAdmins().split(",").clone()));
            accounts.addAll(detailVo.getAdmins());
        }
        if (vo.getDevelops() != null) {
            detailVo.setDevelops(Arrays.asList(vo.getDevelops().split(",").clone()));
            accounts.addAll(detailVo.getDevelops());
        }
        // 2022/5/13 增加工号人员信息
        List<SystemUserDto> userDtos = systemUserService.listUsersByAccount(accounts);
        detailVo.setUsers(userDtos.stream().collect(Collectors.toMap(SystemUserDto::getAccount, a -> a, (a, b) -> b)));
        return detailVo;
    }
}
